/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-05-10
 * Time: 15:01
 */
public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        TreeNode node = new TreeNode(key);
        if (root == null) {
            root = node;
            return true;
        }
        TreeNode ret = root;
        TreeNode pre = null;
        while (ret != null) {
            if (ret.key < key) {
                pre = ret;
                ret = ret.right;
            } else if (ret.key > key) {
                pre = ret;
                ret = ret.left;
            } else {
                return false;
            }
        }
        if (pre.key < key) {
            pre.right = node;
        } else {
            pre.left = node;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode node = root;
        if (node.key < key) {
            node = node.right;
        } else if (node.key > key) {
            node = node.left;
        } else {
            return node;
        }
        return null;
    }
    //删除key的值
    public boolean removeNode(int key) {
        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null) {
            if (cur.key < key) {
                pre = cur;
                cur = cur.right;
            } else if (cur.key > key) {
                pre = cur;
                cur = cur.left;
            } else {
                remove(cur, pre);
            }
        }
        return false;
    }
    public void remove(TreeNode cur, TreeNode pre) {
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
            } else if (cur == pre.left) {
                pre.left = cur.right;
            } else {
                pre.right = cur.right;
            }
        } else if (cur.right == null) {
            if (cur == root) {
                root = cur.left;
            } else if (cur == pre.left) {
                pre.left = cur.left;
            } else {
                pre.right = cur.left;
            }
        } else {
            TreeNode t = cur.right;
            TreeNode tp = cur;
            while (t.left != null) {
                tp = t;
                t = t.left;
            }
            cur.key = t.key;
            if (t == tp.right) {
                tp.right = t.right;
            } else {
                tp.left = t.right;
            }
        }
    }

}
